package com.crh.utils;

import java.sql.*;

/**
 * @author Chrui
 * @date 2018/08/12__13:45
 */
public class JdbcUtils {
    /**
     * 设置数据的账户
     */
    private static String user = "biddinggoods";
    /**
     * 用户的密码
     */
    private static String password = "111111";
    /**
     * JDBC 的数据库url
     * jdbc:oracle:thin:@地址:端口号:实例名
     */
    private static String url = "jdbc:oracle:thin:@localhost:1521:orcl";
    /**
     * oracle驱动
     */
    private static String oracle_driver = "oracle.jdbc.OracleDriver";

    /**
     * 利用静态块加载数据库的驱动
     */
    static {
        try {
            Class.forName(oracle_driver);
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }

    }

    /**
     * 创建连接
     * <p>
     * 利用DriverManager.getConnection创建连接，并抛出异常
     */
    public static Connection getConnection() throws SQLException {
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }

    /**
     * 释放连接
     *
     * @param res  结果集
     * @param st   处理数据库的
     * @param conn 连接
     */
    public static void free(ResultSet res, Statement st, Connection conn) {
        try {
            if (res != null) {
                res.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (st != null) {
                    st.close();
                }
            } catch (Exception e) {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }

    }

}
